package com.ruhua.java.api;

import com.ruhua.java.core.interceptors.ScopeLevel;
import com.ruhua.java.dao.Article;
import com.ruhua.java.dto.ArticleDTO;
import com.ruhua.java.dto.SuccessDTO;
import com.ruhua.java.exception.NotFoundException;
import com.ruhua.java.exception.TrowException;
import com.ruhua.java.repository.ArticleRepository;
import com.ruhua.java.service.ArticleService;
import com.ruhua.java.vo.ResVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;


@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleRepository articleRepository;


    @GetMapping({"/admin/get_all_article","/admin/all_article_name"})
    public ResVO<List> getALLArticle(){
        List<Article> list = articleRepository.findAll();
        return ResVO.go(list);
    }


    @GetMapping("/get_one_article")
    public ResVO<Article> get_article(@RequestParam Long id){
        Article article=articleService.getById(id);
        if(article == null){
            throw new NotFoundException(10001);
        }
        return ResVO.go(article);
    }


    @GetMapping("/type_article")
    public ResVO<List>  type_article(@RequestParam Long type){
        List<Article> list = articleRepository.findByType(type);
        return ResVO.go(list);
    }


    @PutMapping("/admin/ishide")
    @ScopeLevel(10)
    public ResVO<String> isHide(@RequestParam Long id){
        Optional<Article> opItem=articleRepository.findById(id);
        Article article=opItem.orElseThrow(()->new TrowException("文章不存在"));
        Long state=article.getIsHidden()>0?0l:1l;
        article.setIsHidden(state);
        articleRepository.save(article);
        return ResVO.go();
    }

    @PostMapping("/admin/add_article")
    @ScopeLevel(10)
    public ResVO<String> add_article(@RequestBody @Validated ArticleDTO articleDTO){
        articleService.createItem(articleDTO);
        return ResVO.go();
    }

    @PostMapping("/admin/edit_article")
    @ScopeLevel(10)
    public SuccessDTO up_article(@RequestBody @Validated ArticleDTO articleDTO){
        articleService.updateItem(articleDTO);
        return new SuccessDTO();
    }

    @DeleteMapping("/admin/del_article")
    public ResVO<String> del_article(@RequestParam Long id){
        articleService.delItem(id);
        return ResVO.go();
    }


}
